package com.airline.dao;

import com.airline.entity.FlightStock;
import com.airline.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class FlightStockDAO {
    /**
     * 根据航班号查询余票信息
     */
    public FlightStock findByFlightNo(String flightNo) {
        FlightStock stock = null;
        String sql = "SELECT * FROM flight_stock WHERE flight_no = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, flightNo);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                stock = new FlightStock();
                stock.setFlightNo(rs.getString("flight_no"));
                stock.setTotalSeats(rs.getInt("total_seats"));
                stock.setAvailableSeats(rs.getInt("available_seats"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return stock;
    }

    /**
     * 更新余票数量（delta为负数减票，正数加票）
     */
    public void updateAvailableSeats(String flightNo, int delta) {
        String sql = "UPDATE flight_stock SET available_seats = available_seats + ? WHERE flight_no = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, delta);
            pstmt.setString(2, flightNo);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
